import React from 'react'
import { withRouter, Route, Redirect, Switch } from "react-router-dom"
@withRouter
class CompileRoute extends React.Component {
    constructor() {
        super()
        this.state = {
            c: null
        }
    }
    static getDerivedStateFromProps(nextProps) {
        // console.log(nextProps)
        let c = [];//最后处理完之后生成的Route组件
        let { routes, isChildRoute } = nextProps; //路由配置选项
        let { pathname } = nextProps.location; //当前浏览器访问的路径
        let target = routes.find(route => route.path === pathname);
        //通过查找localstorage中有没有token来判断用户是否登入
        let isLogin = localStorage.getItem("qf-token")
        //判断
        //在未登入的情况下 生成这种数据
        // <Route path = "/login" component = "" />
        // <Route path="/404" component={page404} />
        // <Redirect to="/login" />
        if (!isLogin) {//未登入
            //可以返回不需要校验的页面
            c = routes.filter(route => !route.auth)
            c = c.map(route => <Route key={route.path} path={route.path} exact={route.exact} component={route.component} />)
            c.push(<Redirect key="redirect1" to="/login" />)
        } else {
            //登入状态下可以访问所有的页面
            c = routes.map(route => <Route key={route.path} path={route.path} exact={route.exact} component={() => <route.component routes={route.children} />} />)
            // console.log(isChildRoute)
            if (!isChildRoute) {//如果不是嵌套路由,那么就加上重定向
                c.push(<Redirect key="redirect2" to="/404" />)
            }
        }
        // console.log(c)
        return { c }

    }
    render() {
        // console.log(this.props)
        return <Switch>{this.state.c}</Switch>
    }
}

export default CompileRoute